package com.imooc.miaosha.service;

import com.imooc.miaosha.constant.CookieConstant;
import com.imooc.miaosha.dao.UserDao;
import com.imooc.miaosha.domian.User;
import com.imooc.miaosha.exception.GlobalException;
import com.imooc.miaosha.form.LoginForm;
import com.imooc.miaosha.redis.RedisFactory;
import com.imooc.miaosha.redis.keys.UserKey;
import com.imooc.miaosha.result.ResultEnums;
import com.imooc.miaosha.util.CookieUtils;
import com.imooc.miaosha.util.Md5Utils;
import com.imooc.miaosha.util.UuidUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

/**
 * 模块描述: <br>
 * (用户服务层)
 *
 * @Author: Mr. xyb
 * @Date: 2019/4/14 15:23
 * @since: 1.8.0
 * @version: 1.0.0
 */
@Service
public class UserService {

    public User getUserById(Long id) {
        User user = redisFactory.get(UserKey.getById, "" + id, User.class);
        if (user != null) {
            return user;
        }
        user = userDao.getUserById(String.valueOf(id));
        if (user != null) {
            redisFactory.set(UserKey.getById, "" + id, user);
            return user;
        }
        throw new GlobalException(ResultEnums.MOBILE_NOT_EXIST);
    }

    @Transactional(rollbackFor = Exception.class)
    public void addUser() {
        User user = new User();
        user.setId(2L);
        userDao.insert(user);
    }

    public ResultEnums doLogin(LoginForm loginForm) {
        // 判断手机号是否存在
        User user = userDao.getUserById(loginForm.getMobile());
        if (user != null) {
            // 对比密码
            String pass = Md5Utils.formPassToDBPass(loginForm.getPassword(), user.getSalt());
            // 如果密码正确返回用户信息
            if (pass.equals(user.getPassword())) {
                user.setPassword("");


                String token = CookieUtils.getCookie(CookieConstant.COOKIE_NAME_TOKEN);
                if (StringUtils.isEmpty(token)) {
                    token = UuidUtils.uuid();
                }

                UserKey.getToken.setExpireSeconds(CookieConstant.COOKIE_EXPIRE_SECONDS);
                redisFactory.set(UserKey.getToken, token, user);
                CookieUtils.setCookie(CookieConstant.COOKIE_NAME_TOKEN, token, UserKey.getToken.expireSeconds());
                return ResultEnums.LOGIN_SUCCESS;
            } else {
                throw new GlobalException(ResultEnums.LOGIN_ERROR);
            }
        }
        throw new GlobalException(ResultEnums.MOBILE_NOT_EXIST);
    }

    /**
     * 使用cookie的token值从redis中获取用户信息
     * 同时如果用户信息存在，则延长数据的过期时间
     *
     * @param token
     * @return
     */
    public User getUserByToken(String token) {
        if (StringUtils.isEmpty(token)) {
            return null;
        }
        User user = redisFactory.get(UserKey.getToken, token, User.class);
        if (user != null) {
            refreshCache(token, user);
        }
        return user;
    }

    /**
     * 刷新redis缓存以及cookie的过期时间
     *
     * @param token
     * @param user
     */
    private void refreshCache(String token, User user) {
        UserKey.getToken.setExpireSeconds(CookieConstant.COOKIE_EXPIRE_SECONDS);
        redisFactory.set(UserKey.getToken, token, user);
        CookieUtils.setCookie(CookieConstant.COOKIE_NAME_TOKEN, token, CookieConstant.COOKIE_EXPIRE_SECONDS);
    }

    @Autowired
    private UserDao userDao;

    @Autowired
    private RedisFactory redisFactory;

}
